﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Windows.Forms;

namespace Shopfloormanagement.CustomControls
{
    public enum YAxisTitleDirection
    {
        [Description("从下到上")]
        BottomToTop = 0,
        [Description("从上到下")]
        TopToBottom = 1,
        [Description("向左旋转")]
        RotateLeft = 2,
        [Description("向右旋转")]
        RotateRight = 3,
        [Description("水平显示")]
        Horizontal = 4
    }
    public partial class LineChart2 : UserControl
    {
        #region 私有字段
        private List<double> _xValues = new List<double>();
        private List<double> _yValues = new List<double>();
        private Color _lineColor = Color.Blue;
        private float _lineWidth = 2f;
        private bool _showXGrid = true;
        private bool _showYGrid = true;
        private int _padding = 40;
        private Font _labelFont = new Font("Arial", 9);
        private bool _showYLabels = true;
        private Color _labelColor = Color.Black;
        private int _xDecimalPlaces = 0;
        private double _upperLimit = 1;
        private double _lowerLimit = 0;
        private Color _upperLimitColor = Color.Red;
        private Color _lowerLimitColor = Color.Orange;
        private bool _showLimits = true;
        private int _dataLabelDecimalPlaces = 0;
        private bool _enableUpperLimit = false;
        private bool _enableLowerLimit = false;
        private int _yDecimalPlaces = 0;
        private bool _showAxisArrows = true;
        private bool _showXLabels = true;
        private bool _showYAxisLabels = true;
        private string _xAxisText = "X轴";
        private string _yAxisText = "Y轴";
        private bool _showXAxisTitle = true;
        private bool _showYAxisTitle = true;
        private Font _xAxisTitleFont = new Font("Arial", 9);  // X轴标题字体
        private Font _yAxisTitleFont = new Font("Arial", 9);  // Y轴标题字体
        private string _chartLabel1 = "";  // 左上角标签
        private string _chartLabel2 = "";  // 中间标签
        private string _chartLabel3 = "";  // 右上角标签
        private Font _chartLabelFont = new Font("Arial", 9);  // 图表标签字体
        private int _limitDecimalPlaces = 0;  // 上下限值显示的小数位数
        private Font _dataLabelFont = new Font("Arial", 9);  // ��据点标签的字体
        private YAxisTitleDirection _yAxisTitleDirection = YAxisTitleDirection.RotateLeft;
        private bool _yAxisStartFromZero = true;  // 默认Y轴从0开始
        private bool _showLimitLabels = true;  // 新增字段，用于控制是否显示限值文字
        #endregion

        #region 公共属性
        [Category("自定义")]
        [DisplayName("X轴数据")]
        [Description("X轴数据集合")]
        public List<double> XValues
        {
            get => _xValues;
            set
            {
                _xValues = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("Y轴数据")]
        [Description("Y轴数据集合")]
        public List<double> YValues
        {
            get => _yValues;
            set
            {
                _yValues = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("线条颜色")]
        [Description("折线的颜色")]
        public Color LineColor
        {
            get => _lineColor;
            set
            {
                _lineColor = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("显示X轴网格")]
        [Description("是否显示X轴垂直网格线")]
        public bool ShowXGrid
        {
            get => _showXGrid;
            set
            {
                _showXGrid = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("显示Y轴网格")]
        [Description("是否显示Y轴水平网格线")]
        public bool ShowYGrid
        {
            get => _showYGrid;
            set
            {
                _showYGrid = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("线条宽度")]
        [Description("折线宽度")]
        public float LineWidth
        {
            get => _lineWidth;
            set
            {
                _lineWidth = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("边距")]
        [Description("图表的边距大小")]
        public new int Padding
        {
            get => _padding;
            set
            {
                _padding = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("字体")]
        [Description("刻度���签的字体")]
        public Font LabelFont
        {
            get => _labelFont;
            set
            {
                _labelFont = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("显示数据点标签")]
        [Description("是否显示数据点的Y值")]
        public bool ShowYLabels
        {
            get => _showYLabels;
            set
            {
                _showYLabels = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("数据标签字体颜色")]
        [Description("数据点Y值标签的颜色")]
        public Color LabelColor
        {
            get => _labelColor;
            set
            {
                _labelColor = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("X轴小数位数")]
        [Description("X轴标签显示的小数点位数")]
        public int XDecimalPlaces
        {
            get => _xDecimalPlaces;
            set
            {
                if (value >= 0 && value <= 10)
                {
                    _xDecimalPlaces = value;
                    Invalidate();
                }
            }
        }

        [Category("自定义")]
        [DisplayName("限值上限值")]
        [Description("Y值的上限")]
        public double UpperLimit
        {
            get => _upperLimit;
            set
            {
                _upperLimit = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("限值下限值")]
        [Description("Y值的下限")]
        public double LowerLimit
        {
            get => _lowerLimit;
            set
            {
                _lowerLimit = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("限值超上限颜色")]
        [Description("超过上限时的线条颜色")]
        public Color UpperLimitColor
        {
            get => _upperLimitColor;
            set
            {
                _upperLimitColor = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("限值超下限颜色")]
        [Description("低于下限时的线条颜色")]
        public Color LowerLimitColor
        {
            get => _lowerLimitColor;
            set
            {
                _lowerLimitColor = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("限值显示限制线")]
        [Description("是否显示上下线")]
        public bool ShowLimits
        {
            get => _showLimits;
            set
            {
                _showLimits = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("数据标签小数位数")]
        [Description("数据点标签显示的小数点位数")]
        public int DataLabelDecimalPlaces
        {
            get => _dataLabelDecimalPlaces;
            set
            {
                if (value >= 0 && value <= 10)
                {
                    _dataLabelDecimalPlaces = value;
                    Invalidate();
                }
            }
        }

        [Category("自定义")]
        [DisplayName("限值启用上限")]
        [Description("是否启用上限判断和颜色变化")]
        public bool EnableUpperLimit
        {
            get => _enableUpperLimit;
            set
            {
                _enableUpperLimit = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("限值启用下限")]
        [Description("是否启用下限判断和���色变化")]
        public bool EnableLowerLimit
        {
            get => _enableLowerLimit;
            set
            {
                _enableLowerLimit = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("Y轴小数位数")]
        [Description("Y轴标签显示的小数点位数")]
        public int YDecimalPlaces
        {
            get => _yDecimalPlaces;
            set
            {
                if (value >= 0 && value <= 10)
                {
                    _yDecimalPlaces = value;
                    Invalidate();
                }
            }
        }

        [Category("自定义")]
        [DisplayName("显示坐标轴箭头")]
        [Description("是否在坐标轴末端显示箭头")]
        public bool ShowAxisArrows
        {
            get => _showAxisArrows;
            set
            {
                _showAxisArrows = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("显示X轴标签")]
        [Description("是否显示X轴刻度标签")]
        public bool ShowXLabels
        {
            get => _showXLabels;
            set
            {
                _showXLabels = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("显示Y轴标签")]
        [Description("是否显示Y轴刻度标签")]
        public bool ShowYAxisLabels
        {
            get => _showYAxisLabels;
            set
            {
                _showYAxisLabels = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("X轴标题")]
        [Description("X轴的标题文本")]
        public string XAxisText
        {
            get => _xAxisText;
            set
            {
                _xAxisText = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("Y轴标题")]
        [Description("Y轴的标题文本")]
        public string YAxisText
        {
            get => _yAxisText;
            set
            {
                _yAxisText = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("显示X轴标题")]
        [Description("是否显示X轴的标题文本")]
        public bool ShowXAxisTitle
        {
            get => _showXAxisTitle;
            set
            {
                _showXAxisTitle = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("显示Y轴标题")]
        [Description("是否显示Y轴的标题文本")]
        public bool ShowYAxisTitle
        {
            get => _showYAxisTitle;
            set
            {
                _showYAxisTitle = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("X轴标题字体")]
        [Description("X轴标题的字体格式")]
        public Font XAxisTitleFont
        {
            get => _xAxisTitleFont;
            set
            {
                _xAxisTitleFont = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("Y轴标题字体")]
        [Description("Y轴标题的字体格式")]
        public Font YAxisTitleFont
        {
            get => _yAxisTitleFont;
            set
            {
                _yAxisTitleFont = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("图表标签1")]
        [Description("显示在左上角的签文本")]
        public string ChartLabel1
        {
            get => _chartLabel1;
            set
            {
                _chartLabel1 = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("图表标签2")]
        [Description("显示在上方中间的标签文本")]
        public string ChartLabel2
        {
            get => _chartLabel2;
            set
            {
                _chartLabel2 = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("图表标签3")]
        [Description("显示在右上角的标签文本")]
        public string ChartLabel3
        {
            get => _chartLabel3;
            set
            {
                _chartLabel3 = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("图表标签字体")]
        [Description("图表标签的字体格式")]
        public Font ChartLabelFont
        {
            get => _chartLabelFont;
            set
            {
                _chartLabelFont = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("限值小数位数")]
        [Description("上下限值显示的小数点位数")]
        public int LimitDecimalPlaces
        {
            get => _limitDecimalPlaces;
            set
            {
                if (value >= 0 && value <= 10)
                {
                    _limitDecimalPlaces = value;
                    Invalidate();
                }
            }
        }

        [Category("自定义")]
        [DisplayName("数据标签字体")]
        [Description("数据点标签的字体格式")]
        public Font DataLabelFont
        {
            get => _dataLabelFont;
            set
            {
                _dataLabelFont = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("Y轴标题方向")]
        [Description("Y轴标题文字的显示方向")]
        public YAxisTitleDirection YAxisTitleDirection
        {
            get => _yAxisTitleDirection;
            set
            {
                _yAxisTitleDirection = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("Y轴从0开始")]
        [Description("Y轴是否从0开始，否则从数据最小值开始")]
        public bool YAxisStartFromZero
        {
            get => _yAxisStartFromZero;
            set
            {
                _yAxisStartFromZero = value;
                Invalidate();
            }
        }

        [Category("自定义")]
        [DisplayName("限值文字显示")]
        [Description("是否显示上限和下限的文字")]
        public bool ShowLimitLabels
        {
            get => _showLimitLabels;
            set
            {
                _showLimitLabels = value;
                Invalidate();
            }
        }
        #endregion

        #region 构造函数
        public LineChart2()
        {
            //InitializeComponent();
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.UserPaint, true);

            this.Size = new Size(300, 200);
            this.BackColor = Color.White;

            // 设置初始上下限值
            _upperLimit = 1;  // 上限默认为1
            _lowerLimit = 0;  // 下限默认为0

            // 添加默认的X轴和Y据
            _xValues = new List<double> { 1, 2, 3 };
            _yValues = new List<double> { 0, 2, 1 };
        }
        #endregion

        #region 绘图方法


        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);
            Graphics g = e.Graphics;
            g.SmoothingMode = SmoothingMode.AntiAlias;

            // 计算Y轴标签和标题所需的宽度
            float leftMargin = _padding;
            if (_showYAxisLabels || _showYAxisTitle)
            {
                leftMargin = CalculateLeftMargin(g);
            }

            // 计算绘图区域，使算出的左边距
            Rectangle plotArea = new Rectangle(
                (int)leftMargin,  // 使用计算出的左边距
                _padding,
                Width - (int)leftMargin - _padding,  // 调整宽度
                Height - 2 * _padding
            );

            // 绘制边框和背景
            using (Pen borderPen = new Pen(Color.Black, 1))
            {
                g.DrawRectangle(borderPen, plotArea);
            }

            // 如果没有数据，返回
            if (_xValues != null && _yValues != null)
            {

            }
            else
            {
                return;
            }

            if (_xValues.Count == 0 || _yValues.Count == 0 ||
                _xValues.Count != _yValues.Count)
                return;

            // 计算数据范围
            double xMin = _xValues[0], xMax = _xValues[0];
            double yMin, yMax = _yValues[0];

            // 计算X轴范围和Y轴的实际最大值和最小值
            for (int i = 0; i < _xValues.Count; i++)
            {
                xMin = Math.Min(xMin, _xValues[i]);
                xMax = Math.Max(xMax, _xValues[i]);
                yMax = Math.Max(yMax, _yValues[i]);
            }

            // 根据设置决定Y轴最小值
            if (_yAxisStartFromZero)
            {
                yMin = 0;
            }
            else
            {
                // 找出除0外的最小值
                yMin = _yValues.Where(y => y != 0).DefaultIfEmpty(0).Min();
                // 如果所有值都是0，则使用0作为最小值
                if (yMin == 0)
                {
                    yMin = 0;
                }
                else
                {
                    // 为了显示效果，将最小值稍微降低一点
                    yMin = yMin * 0.9;
                }
            }

            // 将Y轴最大值设置为所有Y值中最大值的1.1倍
            yMax = Math.Ceiling(yMax * 1.1);  // 计算Y轴最大值

            // 绘制网格（如果启用）
            if (_showXGrid || _showYGrid)
            {
                DrawGrid(g, plotArea, xMin, xMax, yMin, yMax);
            }

            // 绘制坐标轴
            DrawAxes(g, plotArea, xMin, xMax, yMin, yMax);

            // 绘制限制线
            if (_showLimits)
            {
                DrawLimits(g, plotArea, yMin, yMax);
            }

            // 绘制数据线
            DrawDataLine(g, plotArea, xMin, xMax, yMin, yMax);

            // 绘制图表标签
            DrawChartLabels(g, plotArea);
        }

        private void DrawGrid(Graphics g, Rectangle plotArea,
            double xMin, double xMax, double yMin, double yMax)
        {
            using (Pen gridPen = new Pen(Color.LightGray, 1))
            {
                gridPen.DashStyle = DashStyle.Dash;

                // 绘制垂直网格线（X轴网格）
                if (_showXGrid)
                {
                    foreach (double xValue in _xValues)
                    {
                        int x = plotArea.Left + (int)((xValue - xMin) * plotArea.Width / (xMax - xMin));
                        g.DrawLine(gridPen, x, plotArea.Top, x, plotArea.Bottom);
                    }
                }

                // 绘制水平网格线（Y轴网格）
                if (_showYGrid)
                {
                    int divisions = CalculateYAxisDivisions(plotArea);
                    double[] yValues = CalculateYAxisValues(divisions, yMax);

                    foreach (double value in yValues)
                    {
                        int y = plotArea.Bottom - (int)((value - yMin) * plotArea.Height / (yMax - yMin));
                        if (y >= plotArea.Top && y <= plotArea.Bottom)
                        {
                            g.DrawLine(gridPen, plotArea.Left, y, plotArea.Right, y);
                        }
                    }
                }
            }
        }

        private void DrawAxes(Graphics g, Rectangle plotArea,
            double xMin, double xMax, double yMin, double yMax)
        {
            using (Pen axisPen = new Pen(Color.Black, 1))
            using (SolidBrush textBrush = new SolidBrush(Color.Black))
            using (StringFormat sf = new StringFormat())
            {
                // 设置文本居中对齐
                sf.Alignment = StringAlignment.Far;
                sf.LineAlignment = StringAlignment.Center;

                // 绘制X轴和Y轴的基线，延长一点用于显示箭头
                g.DrawLine(axisPen, plotArea.Left, plotArea.Bottom, plotArea.Right + 20, plotArea.Bottom);  // X轴延长20像素
                g.DrawLine(axisPen, plotArea.Left, plotArea.Bottom, plotArea.Left, plotArea.Top - 20);      // Y轴向上延长20像素

                // 绘制坐标轴箭
                if (_showAxisArrows)
                {
                    // X轴箭头
                    Point[] xArrow = new Point[]
                    {
                        new Point(plotArea.Right + 20, plotArea.Bottom),  // 移动到延长线的末端
                        new Point(plotArea.Right + 12, plotArea.Bottom - 4),
                        new Point(plotArea.Right + 12, plotArea.Bottom + 4)
                    };
                    g.FillPolygon(Brushes.Black, xArrow);

                    // Y轴箭头
                    Point[] yArrow = new Point[]
                    {
                        new Point(plotArea.Left, plotArea.Top - 20),  // 移动到延长线的末端
                        new Point(plotArea.Left - 4, plotArea.Top - 12),
                        new Point(plotArea.Left + 4, plotArea.Top - 12)
                    };
                    g.FillPolygon(Brushes.Black, yArrow);
                }

                // X轴刻度和标签
                if (_showXLabels)
                {
                    foreach (double xValue in _xValues)
                    {
                        int x = plotArea.Left + (int)((xValue - xMin) * plotArea.Width / (xMax - xMin));
                        g.DrawLine(axisPen, x, plotArea.Bottom, x, plotArea.Bottom + 5);

                        string format = "F" + _xDecimalPlaces;
                        string label = xValue.ToString(format);
                        SizeF labelSize = g.MeasureString(label, _labelFont);

                        RectangleF labelRect = new RectangleF(
                            x - labelSize.Width / 2,
                            plotArea.Bottom + 5,
                            labelSize.Width,
                            labelSize.Height
                        );

                        g.DrawString(label, _labelFont, textBrush, labelRect, sf);
                    }
                }

                // Y轴刻度和标签
                DrawYAxisLabels(g, plotArea, yMin, yMax, sf);
            }
        }

        private void DrawLimits(Graphics g, Rectangle plotArea, double yMin, double yMax)
        {
            // 绘制上限线
            if (_upperLimit != double.MaxValue && _enableUpperLimit)
            {
                using (Pen upperLimitPen = new Pen(_upperLimitColor, 1))
                {
                    upperLimitPen.DashStyle = DashStyle.Dash;
                    int y = plotArea.Bottom - (int)((_upperLimit - yMin) * plotArea.Height / (yMax - yMin));
                    y = Math.Max(plotArea.Top, Math.Min(plotArea.Bottom, y)); // 确保y坐标在有效范围内
                    g.DrawLine(upperLimitPen, plotArea.Left, y, plotArea.Right, y);

                    // 根据属性决定是否显示上限文字
                    if (_showLimitLabels)
                    {
                        string label = $"上限: {_upperLimit.ToString($"F{_limitDecimalPlaces}")}";  // 使用指定的小数位数
                        g.DrawString(label, _labelFont, new SolidBrush(_upperLimitColor),
                            plotArea.Right - 60, y - 15);
                    }
                }
            }

            // 绘制下限线
            if (_lowerLimit != double.MinValue && _enableLowerLimit)
            {
                using (Pen lowerLimitPen = new Pen(_lowerLimitColor, 1))
                {
                    lowerLimitPen.DashStyle = DashStyle.Dash;
                    int y = plotArea.Bottom - (int)((_lowerLimit - yMin) * plotArea.Height / (yMax - yMin));
                    y = Math.Max(plotArea.Top, Math.Min(plotArea.Bottom, y)); // 确保y坐标在有效范围内
                    g.DrawLine(lowerLimitPen, plotArea.Left, y, plotArea.Right, y);

                    // 根据属性决定是否显示下限文字
                    if (_showLimitLabels)
                    {
                        string label = $"下限: {_lowerLimit.ToString($"F{_limitDecimalPlaces}")}";  // 使用指定的小数位数
                        g.DrawString(label, _labelFont, new SolidBrush(_lowerLimitColor),
                            plotArea.Right - 60, y + 5);
                    }
                }
            }
        }

        private void DrawDataLine(Graphics g, Rectangle plotArea, double xMin, double xMax, double yMin, double yMax)
        {
            // 检查数据范围是否有效
            if (xMax <= xMin || yMax <= yMin || plotArea.Width <= 0 || plotArea.Height <= 0)
                return;

            using (Pen normalPen = new Pen(_lineColor, _lineWidth))
            using (Pen upperPen = new Pen(_upperLimitColor, _lineWidth))
            using (Pen lowerPen = new Pen(_lowerLimitColor, _lineWidth))
            using (SolidBrush labelBrush = new SolidBrush(_labelColor))
            {
                // 分段绘制线条
                for (int i = 0; i < _xValues.Count - 1; i++)
                {
                    // 添加安全检查，确保不会出现除以零或溢出的情况
                    double xRange = xMax - xMin;
                    double yRange = yMax - yMin;
                    if (xRange == 0) xRange = 1;
                    if (yRange == 0) yRange = 1;

                    // 使用 Math.Max 和 Math.Min 限制坐标范围
                    int x1 = Math.Max(plotArea.Left, Math.Min(plotArea.Right,
                        plotArea.Left + (int)((_xValues[i] - xMin) * plotArea.Width / xRange)));
                    int y1 = Math.Max(plotArea.Top, Math.Min(plotArea.Bottom,
                        plotArea.Bottom - (int)((_yValues[i] - yMin) * plotArea.Height / yRange)));
                    int x2 = Math.Max(plotArea.Left, Math.Min(plotArea.Right,
                        plotArea.Left + (int)((_xValues[i + 1] - xMin) * plotArea.Width / xRange)));
                    int y2 = Math.Max(plotArea.Top, Math.Min(plotArea.Bottom,
                        plotArea.Bottom - (int)((_yValues[i + 1] - yMin) * plotArea.Height / yRange)));

                    double actualY1 = _yValues[i];
                    double actualY2 = _yValues[i + 1];

                    // 如果两点在同一域，直接绘制
                    if ((!_enableUpperLimit && !_enableLowerLimit) ||  // 如果上下限都禁用，使用正常颜色
                        (_enableUpperLimit && actualY1 > _upperLimit && actualY2 > _upperLimit) ||  // 启用上限且超过上限
                        (_enableLowerLimit && actualY1 < _lowerLimit && actualY2 < _lowerLimit) ||  // 启用下限且低于下限
                        (actualY1 >= _lowerLimit && actualY1 <= _upperLimit &&
                         actualY2 >= _lowerLimit && actualY2 <= _upperLimit))  // 在正常范围内
                    {
                        Pen pen = !_enableUpperLimit && actualY1 > _upperLimit ? normalPen :  // 如果禁用上限，使用正常颜色
                                  !_enableLowerLimit && actualY1 < _lowerLimit ? normalPen :  // 如禁用下限，使用常颜色
                                  actualY1 > _upperLimit ? upperPen :  // 启用上限且超过上限，使用红色
                                  actualY1 < _lowerLimit ? lowerPen :  // 启用下限且低于下限，使用黄色
                                  normalPen;  // 其他情况使用正常颜色

                        // 添加额外的安全检查
                        if (x1 >= plotArea.Left && x1 <= plotArea.Right &&
                            x2 >= plotArea.Left && x2 <= plotArea.Right &&
                            y1 >= plotArea.Top && y1 <= plotArea.Bottom &&
                            y2 >= plotArea.Top && y2 <= plotArea.Bottom)
                        {
                            g.DrawLine(pen, x1, y1, x2, y2);
                        }
                        continue;
                    }

                    // 对线段进行分段处理
                    List<PointF> intersectPoints = new List<PointF>();
                    List<double> intersectY = new List<double>();

                    // 添加起点
                    intersectPoints.Add(new PointF(x1, y1));
                    intersectY.Add(actualY1);

                    // 计算与上限的交点
                    if ((actualY1 <= _upperLimit && actualY2 > _upperLimit) ||
                        (actualY1 > _upperLimit && actualY2 <= _upperLimit))
                    {
                        double ratio = (_upperLimit - actualY1) / (actualY2 - actualY1);
                        float intersectX = x1 + (int)((x2 - x1) * ratio);
                        float intersectYPos = plotArea.Bottom - (int)((_upperLimit - yMin) * plotArea.Height / (yMax - yMin));
                        intersectPoints.Add(new PointF(intersectX, intersectYPos));
                        intersectY.Add(_upperLimit);
                    }

                    // 计算与下限的交点
                    if ((actualY1 >= _lowerLimit && actualY2 < _lowerLimit) ||
                        (actualY1 < _lowerLimit && actualY2 >= _lowerLimit))
                    {
                        double ratio = (_lowerLimit - actualY1) / (actualY2 - actualY1);
                        float intersectX = x1 + (int)((x2 - x1) * ratio);
                        float intersectYPos = plotArea.Bottom - (int)((_lowerLimit - yMin) * plotArea.Height / (yMax - yMin));
                        intersectPoints.Add(new PointF(intersectX, intersectYPos));
                        intersectY.Add(_lowerLimit);
                    }

                    // 添加终点
                    intersectPoints.Add(new PointF(x2, y2));
                    intersectY.Add(actualY2);

                    // 按X坐标序交点
                    for (int j = 0; j < intersectPoints.Count - 1; j++)
                    {
                        for (int k = j + 1; k < intersectPoints.Count; k++)
                        {
                            if (intersectPoints[j].X > intersectPoints[k].X)
                            {
                                // 交换点
                                var tempPoint = intersectPoints[j];
                                intersectPoints[j] = intersectPoints[k];
                                intersectPoints[k] = tempPoint;
                                // 交换对应的Y值
                                var tempY = intersectY[j];
                                intersectY[j] = intersectY[k];
                                intersectY[k] = tempY;
                            }
                        }
                    }

                    // 绘制各分段
                    for (int j = 0; j < intersectPoints.Count - 1; j++)
                    {
                        double segmentY1 = intersectY[j];
                        double segmentY2 = intersectY[j + 1];

                        // 确定使用哪种颜色
                        Pen pen;
                        if (_enableUpperLimit && (segmentY1 > _upperLimit || segmentY2 > _upperLimit))
                        {
                            pen = upperPen;
                        }
                        else if (_enableLowerLimit && (segmentY1 < _lowerLimit || segmentY2 < _lowerLimit))
                        {
                            pen = lowerPen;
                        }
                        else
                        {
                            pen = normalPen;
                        }

                        g.DrawLine(pen, intersectPoints[j], intersectPoints[j + 1]);
                    }
                }

                // 绘制数据点和标签
                for (int i = 0; i < _xValues.Count; i++)
                {
                    double xRange = xMax - xMin;
                    double yRange = yMax - yMin;
                    if (xRange == 0) xRange = 1;
                    if (yRange == 0) yRange = 1;

                    int x = Math.Max(plotArea.Left, Math.Min(plotArea.Right,
                        plotArea.Left + (int)((_xValues[i] - xMin) * plotArea.Width / xRange)));
                    int y = Math.Max(plotArea.Top, Math.Min(plotArea.Bottom,
                        plotArea.Bottom - (int)((_yValues[i] - yMin) * plotArea.Height / yRange)));

                    // 选择点的颜色
                    Brush pointBrush;
                    if (_enableUpperLimit && _yValues[i] > _upperLimit)  // 只有启用上限且超过上限时才用红色
                    {
                        pointBrush = new SolidBrush(_upperLimitColor);
                    }
                    else if (_enableLowerLimit && _yValues[i] < _lowerLimit)  // 只有启用下限且低于下限时才用黄色
                    {
                        pointBrush = new SolidBrush(_lowerLimitColor);
                    }
                    else  // 其他所有情况都使用正常颜色
                    {
                        pointBrush = new SolidBrush(_lineColor);
                    }

                    // 绘制点
                    g.FillEllipse(pointBrush, x - 3, y - 3, 6, 6);
                    pointBrush.Dispose();

                    // 绘制标签
                    if (_showYLabels)
                    {
                        string label = _yValues[i].ToString($"F{_dataLabelDecimalPlaces}");
                        SizeF labelSize = g.MeasureString(label, _dataLabelFont);  // 使用新的字体

                        Rectangle labelRect = new Rectangle(
                            x - (int)(labelSize.Width / 2),
                            y - 20,
                            (int)labelSize.Width + 4,
                            (int)labelSize.Height + 2
                        );

                        using (GraphicsPath path = new GraphicsPath())
                        {
                            path.AddRectangle(labelRect);
                            g.FillPath(Brushes.White, path);
                            g.DrawPath(Pens.LightGray, path);
                        }

                        using (StringFormat sf = new StringFormat())
                        {
                            sf.Alignment = StringAlignment.Center;
                            sf.LineAlignment = StringAlignment.Center;
                            g.DrawString(label, _dataLabelFont, labelBrush,  // 使用新的字体
                                new RectangleF(labelRect.X, labelRect.Y,
                                labelRect.Width, labelRect.Height), sf);
                        }
                    }
                }
            }
        }

        private void DrawLabels(Graphics g, Rectangle plotArea,
            double xMin, double xMax, double yMin, double yMax)
        {
            using (SolidBrush labelBrush = new SolidBrush(_labelColor))
            {
                for (int i = 0; i < _xValues.Count; i++)
                {
                    int x = plotArea.Left + (int)((_xValues[i] - xMin) * plotArea.Width / (xMax - xMin));
                    int y = plotArea.Bottom - (int)((_yValues[i] - yMin) * plotArea.Height / (yMax - yMin));

                    string label = $"{_yValues[i]:F1}";
                    SizeF labelSize = g.MeasureString(label, _labelFont);

                    Rectangle labelRect = new Rectangle(
                        x - (int)(labelSize.Width / 2),
                        y - 20,
                        (int)labelSize.Width + 4,
                        (int)labelSize.Height + 2
                    );

                    using (GraphicsPath path = new GraphicsPath())
                    {
                        path.AddRectangle(labelRect);
                        g.FillPath(Brushes.White, path);
                        g.DrawPath(Pens.LightGray, path);
                    }

                    using (StringFormat sf = new StringFormat())
                    {
                        sf.Alignment = StringAlignment.Center;
                        sf.LineAlignment = StringAlignment.Center;
                        g.DrawString(label, _labelFont, labelBrush,
                            new RectangleF(labelRect.X, labelRect.Y,
                            labelRect.Width, labelRect.Height), sf);
                    }
                }
            }
        }

        // 添加新方法用于计算左边距
        private float CalculateLeftMargin(Graphics g)
        {
            float margin = _padding / 2;

            // 计算Y轴标签所需的最大宽度
            if (_showYAxisLabels)
            {
                float maxLabelWidth = 0;
                double[] testValues = { 0, 1000, -1000 };
                foreach (double value in testValues)
                {
                    string label = value.ToString($"F{_yDecimalPlaces}");
                    SizeF labelSize = g.MeasureString(label, _labelFont);
                    maxLabelWidth = Math.Max(maxLabelWidth, labelSize.Width);
                }
                margin += maxLabelWidth + 3;
            }

            // 计算Y轴标题所需的宽度
            if (_showYAxisTitle && !string.IsNullOrEmpty(_yAxisText))
            {
                margin += _showYAxisLabels ? 15 : 35;  // 当只显示标题时使用更大的边距
            }

            return margin;
        }

        // 添加新方法用于绘制图表标签
        private void DrawChartLabels(Graphics g, Rectangle plotArea)
        {
            using (SolidBrush textBrush = new SolidBrush(Color.Black))
            {
                // 绘制左上角标签
                if (!string.IsNullOrEmpty(_chartLabel1))
                {
                    g.DrawString(_chartLabel1, _chartLabelFont, textBrush,
                        5, 5);  // 直接使用控件的左上角坐标
                }

                // 绘制中间标签
                if (!string.IsNullOrEmpty(_chartLabel2))
                {
                    SizeF labelSize = g.MeasureString(_chartLabel2, _chartLabelFont);
                    float x = (Width - labelSize.Width) / 2;  // 使用控件的总宽度来居中
                    g.DrawString(_chartLabel2, _chartLabelFont, textBrush,
                        x, 5);  // 顶部居中
                }

                // 绘制右上角标签
                if (!string.IsNullOrEmpty(_chartLabel3))
                {
                    SizeF labelSize = g.MeasureString(_chartLabel3, _chartLabelFont);
                    float x = Width - labelSize.Width - 5;  // 使用控件的总宽度来计算右边位置
                    g.DrawString(_chartLabel3, _chartLabelFont, textBrush,
                        x, 5);  // 右上角
                }
            }
        }

        // 修改计算Y轴刻度数量的方法
        private int CalculateYAxisDivisions(Rectangle plotArea)
        {
            if (!_yValues.Any()) return 2;  // 如果没有数据，返回默认值

            double maxY = _yValues.Max();
            double minY = _yValues.Min();

            // 根据控件高度计算合适的刻度数量
            const int minPixelsPerDivision = 50;  // 增加每个刻度之间的最小像素距离
            int maxDivisions = plotArea.Height / minPixelsPerDivision;
            maxDivisions = Math.Max(2, Math.Min(maxDivisions, 8));  // 限制刻度数在2-8之间，避免过密

            // 计算Y轴的实际范围
            double range = maxY - minY;
            if (range == 0) range = 1;  // 防止除以零

            // 计算理��的刻度间隔
            double interval = range / maxDivisions;

            // 计算实际的刻度数量
            int divisions = (int)Math.Ceiling(range / interval);
            return Math.Min(divisions, maxDivisions);  // 确保不超过最大刻度数
        }

        // 修改新增方法：计算Y轴刻度值
        private double[] CalculateYAxisValues(int divisions, double maxY)
        {
            List<double> values = new List<double>();

            double minY = _yValues.Min();  // 获取Y值的最小值
            double range = maxY - minY;

            if (range == 0) range = 1;  // 防止除以零

            double interval = range / divisions;  // 计算间隔

            for (int i = 0; i <= divisions; i++)
            {
                values.Add(minY + i * interval);  // 根据最小值和间隔计算刻度值
            }

            return values.ToArray();
        }

        // 修改绘制坐标轴的方法中Y轴标签的部分
        private void DrawYAxisLabels(Graphics g, Rectangle plotArea, double yMin, double yMax, StringFormat sf)
        {
            if (!_showYAxisLabels) return;

            using (SolidBrush textBrush = new SolidBrush(Color.Black))
            {
                int divisions = CalculateYAxisDivisions(plotArea);
                double[] yValues = CalculateYAxisValues(divisions, yMax);

                foreach (double value in yValues)
                {
                    int y = plotArea.Bottom - (int)((value - yMin) * plotArea.Height / (yMax - yMin));
                    if (y >= plotArea.Top && y <= plotArea.Bottom)
                    {
                        string label = value.ToString($"F{_yDecimalPlaces}");
                        g.DrawString(label, _labelFont, textBrush,
                            new RectangleF(plotArea.Left - 50, y - 10, 45, 20), sf);
                    }
                }
            }
        }
        #endregion

        #region 公共方法
        public void AddPoint(double x, double y)
        {
            _xValues.Add(x);
            _yValues.Add(y);
            Invalidate();
        }

        public void ClearPoints()
        {
            _xValues.Clear();
            _yValues.Clear();
            Invalidate();
        }
        #endregion
    }
}
